<script setup>
  import { onMounted, reactive, ref, provide } from 'vue';
  import TabHead from './components/TabHead.vue';
  import TableBody from './components/TableBody.vue';
  import EditAndAdd from './components/EditAndAdd.vue';
  import MapModal from './components/MapModal.vue';
  import api from '@/api/index.js'

  const props = defineProps({
    // 父组件要求的默认筛选参数
    params: { type: Object, default: () => ({}) }
  })
  // 加载状态
  const loading = ref(false)
  // 分页参数
  const pageInfo = reactive({ current: 1, size: 10, total: 0 })
  // 表格数据
  const tableData = ref([])
  // 抽屉节点
  const drawer = ref()
  // 当前数据保存
  const curRow = ref({})

  // 初始化
  const init = (params) => {
    pageInfo.current = 1
    pageInfo.size = 10
    pageInfo.total = 0
    getList(params)
  }

  // 获取表格数据
  const getList = async (params = {}) => {
    loading.value = true
    const data = {
      ...pageInfo,
      ...props.params,
      ...params
    }
    const { data: { records, total } } = await api.getMachineList(data)
    pageInfo.total = total
    tableData.value = records
    loading.value = false
  }

  // 新增数据
  const addItem = () => {
    curRow.value = {}
    drawer.value.open()
  }

  // 编辑数据
  const editItem = (item) => {
    curRow.value = { ...item, children: null }
    drawer.value.open()
  }

  // 关闭弹窗处理
  const closeDrawer = () => {
    curRow.value = {}
  }

  // 页码变化
  const pageChange = page => {
    pageInfo.current = page
    getList(savePara.value)
  }

  // 搜索
  const savePara = ref({})
  const search = (params) => {
    savePara.value = params
    init(params)
  }
  // 地图预览
  const mapModal = ref()
  const point = ref([])
  const xq = (item) => {
    point.value = [item.currentGpsInfo.longitude / 1000000, item.currentGpsInfo.latitude / 1000000]
    mapModal.value.open()
  }

  onMounted(() => {
    init()
  })
  provide('tableData', tableData)
</script>

<template>
  <a-spin :spinning="loading" wrapperClassName="com-spin">
    <div class="com-full page">
      <div class="head">
        <TabHead @add="addItem" @init="search({})" @search="search" />
      </div>
      <div class="table">
        <TableBody :total="pageInfo.total" @pageChange="pageChange" :pageNum="pageInfo.current" @edit="editItem"
          @reload="getList(savePara)" @xq="xq" />
      </div>
    </div>
    <EditAndAdd ref="drawer" :faMenuSltOpt="tableData" :curRow="curRow" @close="closeDrawer" @init="search({})"
      @reload="getList(savePara)" />
    <MapModal ref="mapModal" :point="point" />
  </a-spin>
</template>

<style lang="scss" scoped>
  .page {
    display: flex;
    flex-direction: column;
    gap: 24px;

    .table {
      flex: 1;
      overflow: auto;
    }
  }
</style>